<?php
class system_controller_router_route_default implements system_controller_router_route_interface {
	
	public function match($path) {
		$params = self::parsePath($path);		
		if($params) {
			$this->setRouteIndex(str_replace('_', '/', $params['controller']) . '/' . $params['action']);
		}
		return $params;
	}
	
	protected $_index = null;	
	/**
	 * 设置路由索引key
	 * @return system_controller_router_route_default
	 */
	public function setRouteIndex($index) {
		$this->_index = $index;
		return $this;
	}
	public function getRouteIndex() {
		return $this->_index;
	}
	
	public function assemble($data = array(), $reset = false, $encode = false, $partial = false) {
		if($this->_index != null) {
			$params = self::parsePath($this->_index);	
			if($params) {
				if(is_object($data) && method_exists($data, 'toArray')) {
					$data = $data->toArray();
				}
				$data = $params + $data;
			}
		}		
		$path = '';		
		if(isset($data['controller']) && isset($data['action'])) {			
			$path = str_replace('_', '/', $data['controller']) . '/' . $data['action'];
			unset($data['controller'], $data['action']);			
			foreach($data as $k => $v) {
				$path .= '/' . $k . '/' . urlencode($v);
			}
			return system_controller_front::getInstance()->getBaseUrl() . '/' . ltrim($path);
		}
		throw new system_controller_router_exception('The params can not set controller or action');
	}
	
	static public function parsePath($path) {
		$dispatoher = system_controller_front::getInstance()->getDispatcher();
		if(empty($path)) {
			$path = 'index';
		}
		$pathArray = explode('/', $path);
		$params = array();
		$count = count($pathArray) - 1;
		$action = 'index';
		$controllerClassPre = $dispatoher->getBaseClassPre();
		for($i = $count; $i >= 0; $i--) {
			$class = implode('_', $pathArray);			
			if($dispatoher->loadClass($controllerClassPre . $class)) {				
				if(count($params) > 1) {
					array_pop($params);
					$tmp = array();
					for($i = count($params); $i > 0; $i = $i - 2) {
						$tmp[$params[$i - 1]] = isset($params[$i - 2]) ? urldecode($params[$i - 2]) : '';
					}
					$params = $tmp;
				} else {
					$params = array();
				}
				return array('controller' => $class, 'action' => $action) + $params;
			}
			$params[] = $pathArray[$i];
			$action = $pathArray[$i];
			unset($pathArray[$i]);
		}
		return false;
	}
} 